<template>
  <div class="table-search-page">
    <a-card class="g-mt-10" :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" :form="form" :selfUpdate="true">
          <a-row :gutter="12">
            
            <a-col :md="12" :lg="5" :sm="12" style="padding: 0 4px">
              <a-form-item label="科室"> 
                <a-select
                  placeholder="选择科室"
                  allowClear
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption" 
                  v-model="selectDeptId"
                >
                  <a-select-option  :value="item.id" v-for="(item) in deptList" :key="item.id"> {{item.name}} 
                  </a-select-option>  
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="2" :lg="4" :sm="12">
              <div class="table-page-search-submitButtons g-flex" style="margin-bottom: 4px">
                <!-- <a-icon :type="advanced ? 'up' : 'down'" @click="advanced=!advanced" style="margin-right: 15px;"/> -->
                <a-button type="primary" @click="clickSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="clickReset">重置</a-button>
              </div>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card :bordered="false" class="settlement-form-table">
      <a-button type="primary" @click="springFrameAdd()" class="btn-style-add">新增</a-button>
      <super-table
        ref="table"
        :rowKey="(record, index) => index"
        :columns="columns"
        :data="loadData"
        :bordered="true"
        style="margin-top: 10px"
      >
        <!--序号-->
        <template slot="index" slot-scope="text, record, index">
          <span>{{ (queryParam.pageNum - 1) * queryParam.pageSize + (index + 1) }}</span>
        </template>
        <!-- 是否次日 --> 
        <span slot="isday" slot-scope="tags">
          <a-tag :color="tags == 0 ? '#39f' : 'green'">
            {{ tags == 0 ? '否': '是' }}
          </a-tag>
        </span>

        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <div style="margin: 0 auto">
            <a-button class="btn-class-no-border" style="padding: 0" type="link" @click="editClick(record)"
              >编辑</a-button
            >

            <!-- <a-popconfirm title="作废该项数据?" @confirm="() => handRemove(record)">
              <a  class="btn-class-no-border">作废</a>
            </a-popconfirm> -->
          </div>
        </template>
      </super-table>
    </a-card>

    <!-- 新增 -->
    <spring-frame ref="springFrame" :row_record="current_row_record"></spring-frame>
  </div>
</template>

<script>
import { shiftTypeSelectTpshiftType, SchedulingDeleteTbShift, shiftTypeSelectTgbDepartmentGroup } from '@/api/modular/main/rosterList/rosterList'
import { SuperTable, upTime } from '@/components'
import moment from 'moment'
import springFrame from '@/views/workforceManagement/shiftList/components/springFrame'
import editComponents from '@/views/workforceManagement/shiftList/components/editComponents'

// 监听
var localStorageMock = (function (win) {
  var storage = win.localStorage
  return {
    setItem: function (key, value) {
      var setItemEvent = new Event('setItemEvent')
      var oldValue = storage[key]
      setItemEvent.key = key
      // 新旧值深度判断，派发监听事件
      if (oldValue !== value) {
        setItemEvent.newValue = value
        setItemEvent.oldValue = oldValue
        win.dispatchEvent(setItemEvent)
        storage[key] = value
        return true
      }
      return false
    },
    getItem: function (key) {
      return storage[key]
    },
    removeItem: function (key) {
      storage[key] = null
      return true
    },
    clear: function () {
      storage.clear()
      return true
    },
    key: function (index) {
      return storage.key(index)
    },
  }
})(window)

Object.defineProperty(window, 'localStorage', { value: localStorageMock, writable: true })

export default {
  components: {
    SuperTable,
    upTime,
    springFrame,
    editComponents,
  },

  data() {
    return {
      dataSource: [],
      loadData: (parameter) => {
        this.queryParam.pageNum = parameter.pageNum
        this.queryParam.pageSize = parameter.pageSize
        return shiftTypeSelectTpshiftType(this.queryParam).then((res) => {
          this.loading = false //关闭加载
          res.rows.map((item) => {
            item.action = '操作'
          })
          this.dataSource = [...res.rows]
          res.rows = this.rowSpan('deptName')

          let newData = Object.assign({}, res)
          return newData
        })
      },
      form: this.$form.createForm(this),
      advanced: false, // 高级搜索 展开/关闭
      current_row_record: {},
      columns: [
        {
          title: '科室',
          align: 'center',
          dataIndex: 'deptName',
          width: 120,
          ellipsis: true,
          customRender: (text, record) => {
            return {
              children: text,
              attrs: {
                rowSpan: record.deptNameRowSpan,
              },
            }
          },
        },
        { title: '序号', scopedSlots: { customRender: 'index' }, align: 'center', width: 80 },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'name',
          width: 100,
          ellipsis: true,
          customRender: (text, record) => {
            return {
              children: text,
              attrs: {
                rowSpan: record.nameRowSpan,
              },
            }
          },
        },
        {
          title: '是否次日',
          align: 'center',
          dataIndex: 'isday',
          width: 100,
          ellipsis: true,
          scopedSlots: { customRender: 'isday' }, 
        },
        {
          title: '别名别名',
          align: 'center',
          dataIndex: 'wxworkName',
          width: 140,
          ellipsis: true,
          customRender: (text, record) => {
            return {
              children: text,
              attrs: {
                rowSpan: record.wxworkNameRowSpan,
              },
            }
          },
        },
        {
          title: '开始时间',
          align: 'center',
          dataIndex: 'begin',
          width: 150,
          ellipsis: true,
          customRender: (text, record) => {
            return {
              children: text,
              attrs: {
                rowSpan: record.beginRowSpan,
              },
            }
          },
        },
        {
          title: '结束时间',
          align: 'center',
          dataIndex: 'end',
          width: 150,
          ellipsis: true,
          customRender: (text, record) => {
            return {
              children: text,
              attrs: {
                rowSpan: record.endRowSpan,
              },
            }
          },
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 80,
          style:'border-left:1px solid',
          customRender: (text, record) => {
            const props = {
              record: record,
            }
            return {
              children: <edit-components {...{ props }}> </edit-components>,
              attrs: {
                rowSpan: record.deptNameRowSpan,
              },
            }
          },
        },
      ],

      // 查询参数
      queryParam: {
        pageNum: 1, //第几页
        pageSize: 10, //每页中显示数据的条数
        current: 1,
        type: 1,
        begintime: undefined,
        endtime: undefined,
        chargeType: 1,
        reportType: 2,
      },
      loading: true, //加载状态,

      // 时间
      gettime: '',
      watchBool: false,
      tegistrationTime: [],
      searchUserName: '',
      selectDeptId: undefined,
      deptList: [],
    }
  },
  created() {
    shiftTypeSelectTgbDepartmentGroup().then(res => {
      if(res.code == 200){
        this.deptList = [...res.rows]
      }else{
        this.$message.error(res.msg)
      }
    })
  },

  watch: {
    watchBool() {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = 10
      this.queryParam.current = 1
      this.queryParam = Object.assign({}, this.queryParam)
      console.log(this.queryParam)
    },
  },
  mounted() {
    let that = this
    window.addEventListener('setItemEvent', (e) => {
      that.$nextTick(() => {
        that.$refs.table.loadData()
      })
    })
  },
  methods: {
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    // 合并
    rowSpan(key) {
      let arr = this.dataSource
        .reduce((result, item) => {
          if (result.indexOf(item[key]) < 0) {
            result.push(item[key])
          }
          return result
        }, [])
        .reduce((result, keys) => {
          const children = this.dataSource.filter((item) => item[key] === keys)
          result = result.concat(
            children.map((item, index) => ({
              ...item,
              [`${key}RowSpan`]: index === 0 ? children.length : 0,
            }))
          )
          return result
        }, [])
      this.dataSource = arr
      console.log(this.dataSource)
      return arr
    },
    // 编辑
    editClick(record) {
      this.current_row_record = record
      this.$nextTick(() => {
        this.$refs.springFrame.show('edit')
      })
    },
    handRemove(record) {
      let sendData = {
        userId: record.userId,
        createTime: record.createTime,
      }
      SchedulingDeleteTbShift(sendData).then((res) => {
        if (res.code == 200) {
          this.$refs.table.loadData()
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 新增
    springFrameAdd() {
      this.$refs.springFrame.show()
    },
 

    // 获取当前的日期
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh = new Date().getHours()
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss
    },

    checkPattern(str) {
      const pattern = new RegExp('[\u4E00-\u9FA5]+')
      if (pattern.test(str)) {
        return true
      }
      return false
    },

    moment,
    toCountDown(time) {
      //1000代表1秒，1000*60代表60分钟
      return Date.now() + parseInt(time) * 1000
    },
    minutesToSeconds(time) {
      return parseInt(time)
    },

    //点击查询-高级搜索
    clickSearch() {
      this.watchBool = !this.watchBool
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = 10
      this.queryParam.current = 1

      let form_values = {} 
       
      form_values.deptId = this.selectDeptId

      this.queryParam = Object.assign(this.queryParam, form_values)

      this.$nextTick(() => {
        this.$refs.table.loadData()
      })
    },
    clickReset() {
      let form_values = {} 
      this.selectDeptId = '' 
      form_values.deptId = undefined

      this.queryParam = Object.assign(this.queryParam, form_values)
    },
  },
}
</script>

<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
  margin-bottom: 2px;
}

.currentRowClass {
  background: #e6f7ff;
}

/deep/ .ant-tabs-bar {
  // border-bottom: none;
  border-bottom: 1px solid #e8e8e8;
}

/deep/ .ant-badge-count,
.ant-badge-dot,
.ant-badge .ant-scroll-number-custom-component {
  right: -10px;
}

/deep/ .settlement-form-table {
  .ant-table-small.ant-table-bordered .ant-table-fixed-right {
    border-left: 0 !important;
    border-right: 0 !important;
  }
}
/deep/ .btn-style-add {
  margin-top: 20px;
}
/deep/ .not-border-btn-style,
/deep/ .not-border-btn-style:hover {
  font-size: 14px;
  border: 0;
  line-height: 5px;
  border-color: rgba(255, 255, 255, 0) !important;
}

/deep/ .btn-class-no-border {
  border-color: transparent !important;
  padding: 0;
  color: #5badff;
  font-size: 13px;
}
/deep/ .ant-table-bordered .ant-table-thead > tr > th, 
/deep/ .ant-table-bordered .ant-table-tbody > tr > td{
  border-left: 1px solid #e8e8e8 !important;
}
</style>